import request from '../utils/request';

/**
 * 用户登录
 * @param {Object} credentials - 登录凭证
 * @param {string} credentials.username - 用户名
 * @param {string} credentials.password - 密码
 * @returns {Promise} - 返回登录结果
 */
export const login = async (credentials) => {
  try {
    const response = await request.post('/auth/login', credentials);
    // 后端返回的格式是 { success: true, message: "登录成功", data: { token: "...", user: {...} } }
    if (response.success && response.data && response.data.token) {
      localStorage.setItem('token', response.data.token);
      localStorage.setItem('user', JSON.stringify(response.data.user));
    }
    return response;
  } catch (error) {
    throw error.response ? error.response.data : { message: '网络错误，请稍后再试' };
  }
};

/**
 * 用户注册
 * @param {Object} userData - 用户数据
 * @param {string} userData.username - 用户名
 * @param {string} userData.password - 密码
 * @param {string} userData.nickname - 昵称
 * @returns {Promise} - 返回注册结果
 */
export const register = async (userData) => {
  try {
    const response = await request.post('/auth/register', userData);
    return response;
  } catch (error) {
    throw error.response ? error.response.data : { message: '网络错误，请稍后再试' };
  }
};

/**
 * 退出登录
 */
export const logout = () => {
  localStorage.removeItem('token');
  localStorage.removeItem('user');
  // 触发用户登出事件
  window.dispatchEvent(new CustomEvent('user-logout'));
};

/**
 * 获取当前用户信息
 * @returns {Promise} - 返回用户信息
 */
export const getCurrentUser = async () => {
  try {
    const response = await request.get('/users/profile');
    // 经过 request 响应拦截器，这里收到的是 ApiResponse
    // 返回后端的 data 字段（即用户对象）
    return response.data;
  } catch (error) {
    throw error.response ? error.response.data : { message: '网络错误，请稍后再试' };
  }
};

/**
 * 更新用户资料
 * @param {Object} userData - 用户数据
 * @returns {Promise} - 返回更新结果
 */
export const updateProfile = async (userData) => {
  try {
    const response = await request.put('/users/profile', userData);
    // 返回更新后的用户对象
    return response.data;
  } catch (error) {
    throw error.response ? error.response.data : { message: '网络错误，请稍后再试' };
  }
};
